import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:speed_random/core/http/ws_app_test.dart';
import '../../core/services/in_app_purchase_service.dart';
import '../../core/types/product_details.dart';
import '../../core/types/purchase_details_zdy.dart';

class IosPurchaseService implements InAppPurchaseService<PurchaseDetails> {
  final InAppPurchase _iap = InAppPurchase.instance;
// 定义 _purchaseSubscription
  StreamSubscription<List<PurchaseDetails>>? _purchaseSubscription;

  @override
  Future<void> initialize() async {
    WidgetsFlutterBinding.ensureInitialized();
    // 可添加更多初始化逻辑
  }

  @override
  /// 恢复购买
  Future<void> restorePurchases() async {
    try {
      //// restorePurchases() 方法用于 恢复用户之前的非消耗型购买（如永久解锁、订阅等）。以下是它的完整使用方法和注意事项：
      //     //适用场景：当用户更换设备或重装应用时，恢复其已购买的非消耗型商品/订阅。
      //     // 如果初始购买时指定了 applicationUserName（用于关联用户账号），恢复时需传入相同的值
      //     //await _iap.restorePurchases(applicationUserName: "user_123");
      await _iap.restorePurchases(); // 触发恢复操作
    } catch (e) {
      print("恢复购买失败: $e");
    }
  }
  /// 购买商品
  /// [productId] 商品 ID
  /// [applicationUserName] 应用用户名
  /// [productType] 商品类型 consumable 消耗型商品（可重复购买） nonConsumable 非消耗型商品(只能支付一次)
  @override
  Future<bool> buyProduct(String productId,{String? applicationUserName,String? productType='consumable'}) async {
    try {
      final ProductDetailsResponse response = await _iap.queryProductDetails({productId});
      if (response.notFoundIDs.isEmpty) {
        final ProductDetails productDetails = response.productDetails.first;
        final PurchaseParam purchaseParam = PurchaseParam(
            productDetails: productDetails,
            applicationUserName: applicationUserName
        );
        if (productType == 'consumable') {
          return await _iap.buyConsumable(purchaseParam: purchaseParam);
        } else {
          return await _iap.buyNonConsumable(purchaseParam: purchaseParam);
        }
      }
    } catch (e) {
      print("购买商品失败: $e");
    }
    // 确保在所有可能的执行路径上都有返回值
    return false;
  }



  @override
  Future<List<ProductDetailsZdy>> getAvailableProducts(List<String> productIds) async {
    final ProductDetailsResponse response = await _iap.queryProductDetails(productIds.toSet());
    wsPrint(response);
    return response.productDetails.map((e) {
      wsPrint(e);
      return ProductDetailsZdy(
        id: e.id,
        title: e.title,
        description: e.description,
        price: e.price,
        rawPrice: e.rawPrice,
        currencyCode: e.currencyCode,
        currencySymbol: e.currencySymbol,
      );
    }).toList();
  }

  /// 注册购买更新监听
  /// [handlePagePurchases] 处理购买事件的回调函数
  Future<void> purchaseUpdates({Function(PurchaseDetailsZdy purchaseDetails)? onPurchased}) async {
    // 在购买页面设置专属监听
    _purchaseSubscription = _iap.purchaseStream.listen((purchases) {
      _handlePagePurchases(purchases, onPurchased: onPurchased); // 处理页面内的购买事件
    }) ;
  }

  @override
  Future<void> cancelPurchaseUpdates() async {
    await _purchaseSubscription?.cancel();
    _purchaseSubscription = null;
  }

  // 购买支付成功后回调。处理购买成功事件。
  void _handlePagePurchases(List<PurchaseDetails> purchases,
      {Function(PurchaseDetailsZdy purchaseDetails)? onPurchased}) async {
    //print(purchases.length);
    for (final purchase in purchases) {
      //print("object: ${purchase.productID}");
      //print("serverVerificationData: ${purchase.verificationData.serverVerificationData}");
      //print("purchaseID: ${purchase.purchaseID}");
      //print("status: ${purchase.status}");
      //print("pendingCompletePurchase: ${purchase.pendingCompletePurchase}");
      String status="";
      try {
        switch (purchase.status) {
          case PurchaseStatus.purchased:
            print("页面内捕获购买: ${purchase.productID}");
            status="purchased";
            // 处理购买成功 UI（如显示感谢弹窗）
            //EasyLoading.showSuccess('购买成功'.tr);
            // 调用 API 验证购买
            // _verifyPurchase(purchase.productID,purchase.purchaseID,"${_orderId}", purchase.verificationData.serverVerificationData);
            break;
          case PurchaseStatus.pending:
            status="pending";
            // EasyLoading.showInfo('购买处理中，请稍候'.tr);
            break;
          case PurchaseStatus.error:
            status="error";
            // EasyLoading.showError('购买出错: ${purchase.error?.message}'.tr);
            break;
          case PurchaseStatus.restored: // 恢复购买 用户点击,谷歌重新返回 直接购买记录验证 永久会员
            status="restored";
            // _verifyPurchase(purchase.productID,purchase.purchaseID,"${_orderId}", purchase.verificationData.serverVerificationData);
            // EasyLoading.showSuccess('购买已恢复'.tr);
            break;
          case PurchaseStatus.canceled:
            status="canceled";
            // EasyLoading.showInfo('购买已取消'.tr);
            break;
        }

        // 完成购买流程  	pendingCompletePurchase	bool 是否未调用 completePurchase()（消耗型商品必须调用）
        if (purchase.pendingCompletePurchase) {
          await _iap.completePurchase(purchase);
        }

        onPurchased?.call(PurchaseDetailsZdy(
          status: status,
          purchaseID: "${purchase.purchaseID}",
          productID: "${purchase.productID}",
          serverVerificationData: "${purchase.verificationData.serverVerificationData}",
          errorMessage: "${purchase.error?.message}",
        ));
      } catch (e) {
        print('处理购买事件出错: $e');
        // EasyLoading.showError('处理购买事件出错，请重试'.tr);
      }
    }
  }

}
